package com.Kritsana_Ding.project_ev_send;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements LocationListener{
	
	private EditText etName;
	private Spinner spnLine;
	private Spinner spnNo;
	private Button btnSubmit;
	private TextView tvShow;
	
	private LocationManager lm;
	
	private String get_Name = "";
	private String get_Line = "";
	private String get_No   = "";
	
	private String Lat  = "Lat";
	private String Lon  = "Lon";
	private String Spe  = "Speed";
	private String code = "Error";
    private String msg  = "Error";
	
	private String url  = "";
	
	private boolean status_server = false;
	
	public static final String PREFS_NAME = "MyPrefsFile";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
		
		intit();
		checkInternet();
		
		btnSubmit.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(status_server == false){
					get_Name = etName.getText().toString();
					get_Line = spnLine.getSelectedItem().toString();
					get_No = spnNo.getSelectedItem().toString();
					
					
					SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			        SharedPreferences.Editor editor = settings.edit();
			        editor.putString("get_Name", get_Name);
			        editor.putString("get_Line", get_Line);
			        editor.putString("get_No", get_No);
			        editor.commit();
					
					
					etName.setEnabled(false);
					spnLine.setEnabled(false);
					spnNo.setEnabled(false);
					btnSubmit.setEnabled(false);
					btnSubmit.setText("Sign In");
					status_server = true;
					
				}
				else{
					get_Name = etName.getText().toString();
					get_Line = spnLine.getSelectedItem().toString();
					get_No = spnNo.getSelectedItem().toString();
					etName.setEnabled(false);
					spnLine.setEnabled(false);
					spnNo.setEnabled(false);
					btnSubmit.setEnabled(false);
					btnSubmit.setText("Sign Out");
					status_server = false;
					
				}
				
			}
		});
	}


	private void intit() {
		// TODO Auto-generated method stub
		etName    = (EditText) findViewById(R.id.editTextName);
		spnLine   = (Spinner) findViewById(R.id.spinnerLine);
		spnNo     = (Spinner) findViewById(R.id.spinnerNo);
		btnSubmit = (Button) findViewById(R.id.buttonSubmit);
		tvShow    = (TextView) findViewById(R.id.textViewShow);
		
		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onLocationChanged(Location loc) {
		// TODO Auto-generated method stub
		JSONObject data = new JSONObject();
		try {
			Lat = Double.toString(loc.getLatitude());
			Lon = Double.toString(loc.getLongitude());
			Spe = Double.toString(loc.getSpeed()+0.000001);
			
			url = "http://inear3g.embeddednu.com/apis/send_data/evnu2013/" + get_No + "/" + get_Line + "/" + Lat + "/" + Lon + "/0/" + Spe + "/" + get_Name;
			
			if(status_server){
				data = json(url);
	            code = data.getString("code");
	            msg  = data.getString("msg");
			}
			
	        	
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		tvShow.setText("Name : " + get_Name + "\n" +
			       "No   : " + get_No + "\n" +
			       "Line : " + get_Line + "\n" +
			       "Lat  : " + Lat + "\n" +
			       "Lon  : " + Lon + "\n" +
			       "Speed: " + Spe + "\n" +
			       "Code : " + code + "\n" +
			       "Msg  : " + msg + "\n");
			       //"Url  : " + url );
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
		//startService(new Intent(this, MyService.class));
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		lm.removeUpdates(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		stopService(new Intent(this, MyService.class));
		try {
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		    get_No = settings.getString("get_No", "null");
			json("http://inear3g.embeddednu.com/deleteall.php?no="+get_No);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		startService(new Intent(this, MyService.class));
	}


	public boolean checkInternet() {
        ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected() == true) {
            Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
            //tvShow.setText("Network Available");
            return true;
        } else {
            Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
            //tvShow.setText("Network Not Available");
            return false;
        }
    }
	
	public String getJSONUrl(String urls) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urls);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                //				Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    public JSONObject json(String url) throws JSONException {
        JSONObject mainJson = new JSONObject(getJSONUrl(url));
        mainJson.getString("code");
        mainJson.getString("msg");
        
        /*
        JSONArray jsonArray = mainJson.getJSONArray("data_list");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject objJson = jsonArray.getJSONObject(i);
            objJson.getString("distance");
            objJson.getString("date");
            objJson.getString("time");
            objJson.getString("timenow");
            objJson.getString("label");
        }
        
        */
        
        return mainJson;
    }

}
